package com.bwjf.authority.commons.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bwjf.authority.entity.AuthorityUser;

/**
 * web请求，session操作工具类。
 * @author llq
 */
public class WebRequestUtil {
    
    private final static String SESSION_USER_KEY="user";
    
    /**
     * 获取session中的user对象
     * @return
     */
    public static AuthorityUser getSessionUser(){
        return (AuthorityUser)getSessionAttribute(SESSION_USER_KEY);
    }
    
    /**
     * 向session写入user对象
     * @param user
     */
    public static void setSessionUser(AuthorityUser user){
        HttpSession session=getSession();
        session.setAttribute(SESSION_USER_KEY, user);
    }
    
    /**
     * 从session中获取数据
     * 可在任意java bean中使用
     * @param key
     * @return
     */
    public static Object getSessionAttribute(String key){
        HttpSession session=getSession();
        return session.getAttribute(key);
    }
    
    /**
     * 向session中写入数据
     * @param key
     * @param data
     */
    public static void setSessionAttribute(String key,Object data){
        HttpSession session=getSession();
        session.setAttribute(key, data);
    }
    
    /**
     * 获取url根路径
     * @return
     */
    public static String getBasePathURL(){
        HttpServletRequest request=getRequest();
        return getBasePathURL(request);
    }
    
    /**
     * 获取url根路径
     * @return
     */
    public static String getBasePathURL(HttpServletRequest request){
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        return basePath;
    }
    
    /**
     * 获取session
     * @return
     */
    private static HttpSession getSession(){
        HttpSession session=getRequest().getSession();
        return session;
    }
    
    /**
     * 获取request
     * @return
     */
    private static HttpServletRequest getRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }
}
